package door.smartlift.top.config;


import door.smartlift.top.common.utils.JsonUtil;
import org.apache.commons.io.IOUtils;

import org.apache.shiro.authc.AuthenticationToken;

import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 * @author admin
 * @date 2017/12/25
 */
public class MyFormAuthenticationFilter extends FormAuthenticationFilter {


    @Override
    public void setLoginUrl(String loginUrl) {
        super.setLoginUrl("/sys/login");
    }


    @Override
    protected AuthenticationToken createToken(ServletRequest request, ServletResponse response) {

        StringBuilder sb = new StringBuilder();
        BufferedReader reader = null;
        Map map=new HashMap();
        try {
            reader = request.getReader();
            List<String> list= IOUtils.readLines(reader);
            for (String s:list){
                sb.append(s);
            }

            map= (Map) JsonUtil.stringToObj(sb.toString().trim(), Map.class);
            System.out.print(map);
        } catch (IOException e) {
            e.printStackTrace();
        }
        String username = (String) map.get("username");
        String password = (String) map.get("password");

        return createToken(username, password, request, response);

    }

    @Override
    protected void issueSuccessRedirect(ServletRequest request, ServletResponse response) throws Exception {
        request.getRequestDispatcher("/sys/index").forward(request,response);
    }

}
